<!-- 富文本框 -->
<template>
  <a-spin class="spin-container" :loading="loading" :tip="loadingTips">
    <div class="wangeditor-container">
      <div class="editor-bg">
        <!-- 菜单栏 -->
        <div class="card-header">
          <Toolbar
            class="toolbar"
            :editor="editorRef"
            :defaultConfig="toolbarConfig"
          />
          <slot name="price-value"></slot>
        </div>
        <slot name="order-consult"></slot>
        <!-- 内容 -->
        <div class="card-body" ref="scrollTop">
          <div class="editor-wrapper">
            <!-- 标题 -->
            <a-input
              autocomplete="off"
              :placeholder="'请输入标题'"
              :max-length="maxTitleLength"
              show-word-limit
              class="editor-title"
              v-model="title"
              size="large"
              @input="handleInputTitle"
              ref="editorTitleRef"
            ></a-input>
            <div class="editor-container">
              <Editor
                ref="editorValueRef"
                v-model="valueHtml"
                class="editor-content"
                :defaultConfig="editorConfig"
                @onCreated="handleCreated"
                @onChange="handleChange"
                @onDestroyed="handleDestroyed"
                @onFocus="handleFocus"
                @onBlur="handleBlur"
                @customAlert="customAlert"
                @customPaste="customPaste"
              />
            </div>
          </div>
          <div class="scroll-bottom" ref="scrollBottom"></div>
        </div>
      </div>
      <!-- 页脚按钮 -->
      <div class="card-footer">
        <div class="footer">
          <div class="footer-set">
            <a-button
              type="primary"
              class="btn-btn-primary-light flex-reverse"
              @click="toggleScrollPosition"
            >
              <span>返回顶部</span>
            </a-button>
          </div>
          <a-space class="button-group">
            <p class="total-length">
              字数:
              <span id="total-length"
                ><b :style="wordCountColor">{{ currentWordCount }}</b
                >/{{ maxLength }}
              </span>
            </p>
            <a-button
              type="primary"
              @click="handleSubmit"
              :disabled="disabledFlag"
            >
              发布</a-button
            >
          </a-space>
        </div>
      </div>
    </div>
    <!-- 导入文档 -->
    <PublickModal
      :modalWidth="'520px'"
      :modalStyle="'modal-pub'"
      v-model:visible="uploadDocxVisible"
      title="导入文档"
      :footer="false"
      @cancel="uploadDocxCancel"
    >
      <UploadDocx
        :articleType="articleType"
        @uploadDocxConfirm="uploadDocxConfirm"
        @setLoadingFlag="setLoadingFlag"
      />
    </PublickModal>
    <!-- 话题管理 -->
    <PublickModal
      :modalWidth="'1140px'"
      :modalStyle="'modal-pub'"
      v-model:visible="insertTopicVisible"
      title="话题管理"
      @cancel="insertTopicCancel"
      @ok="insertTopicConfirm"
    >
      <InsertTopic ref="insertTopicRef" insertTopicType="insertTopicType" />
    </PublickModal>
    <!--@联系人管理-->
    <PublickModal
      :modalWidth="'520px'"
      :modalStyle="'modal-pub'"
      v-model:visible="insertAtVisible"
      title="选择联系人"
      @cancel="insertAtCancel"
      @ok="insertAtConfirm"
    >
      <InsertAt ref="insertAtRef" insertAtType="insertAtType" />
    </PublickModal>
    <!-- 打开历史 -->
    <a-drawer
      popup-container="#parentNode"
      :visible="hisotryVisible"
      :mask-closable="true"
      :width="183"
      :drawer-style="{ boxShadow: '0 0 8px 0px rgba(0, 0, 0, 0.01)' }"
      class="a-drawer-history"
      style="padding: 0; margin: 0"
      @cancel="hideDraftHistoryModal"
      :footer="false"
    >
      <template #title>历史版本</template>
      <ul class="history-record" style="margin: 0; padding: 0"></ul>
    </a-drawer>
  </a-spin>
</template>

<script setup lang="ts">
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import "./wangeditor.less"; // 自定义富文本编辑器样式

import {
  onBeforeUnmount,
  ref,
  shallowRef,
  nextTick,
  onMounted,
  watchEffect,
  computed,
  onUnmounted,
} from "vue";

import {
  handlePasteImage,
  handlePasteHtmlStyle,
  extractEditorImagesInfo,
  extractEditorSubjectTalks,
} from "./utils/handleImagesInArticle";
// 引入的方法  处理图片  处理文本等
import {
  filterHtmlTagsAndConvertToSpace,
  truncateHtmlWithLinksAndBr,
  truncateHtmlWithTags,
} from "./utils/tool";

import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { IDomEditor, IToolbarConfig, DomEditor } from "@wangeditor/editor";
import { Transforms } from "slate";

import { Message } from "@arco-design/web-vue";

// 引入 脚本
import useLoading from "@/hooks/loading";
import { debounce } from "lodash";
import { sleep } from "@/hooks/sleep";

// 注册菜单
import registerMenu from "./utils/registerMenu";
// 注册自定义dom结构
import registerNode from "./utils/registerNode";

// 修改 插入 链接
import { insertLink, updateLink } from "./module/customLink/menu/updateLink";
import { updateLinkCard } from "./module/converToLinkCard/menu/updateLinkCard";
// 插入提醒
import { insertMention } from "./module/mention/insertMention";

// 引入的组件
import UploadDocx from "./components/uploadDocx.vue";
import InsertTopic from "./components/insertTopic.vue";
import InsertAt from "./components/insertAt.vue";

import { useArticleStore } from "@/store";
import { setItem, getItem, removeItem } from "@/utils/storage";

const { onCurrent, emitCurrent } = useMitt();
const articleStore = useArticleStore();
const userInfo: any = getUserInfo();

// 定义打开弹窗的事件
// At联系人
const insertAtVisible = ref<boolean>(false);
const insertAtType = ref<string>("keyboard");
const showAtModal = (type: string) => {
  insertAtVisible.value = true;
  insertAtType.value = type;
};
const hideAtModal = () => {
  insertAtVisible.value = false;
};

// 话题
const insertTopicVisible = ref<boolean>(false);
const insertTopicType = ref<string>("keyboard");
const showTopicModal = (type: string) => {
  insertTopicVisible.value = true;
  insertTopicType.value = type;
};
const hideTopicModal = () => {
  insertTopicVisible.value = false;
};

// 导入文本
const uploadDocxVisible = ref<boolean>(false);
const showUploadDocxModal = () => {
  uploadDocxVisible.value = true;
};
const hideUploadDocxModal = () => {
  uploadDocxVisible.value = false;
};
// 打开历史
const hisotryVisible = ref<boolean>(false);
const showDraftHistoryModal = () => {
  historyList();
  hisotryVisible.value = true;
};
const hideDraftHistoryModal = () => {
  hisotryVisible.value = false;
  // 编辑器获取焦点
  editorFocus();
};

// 内容 HTML
const { loading, setLoading } = useLoading(false);
const loadingTips = ref("加载中，请稍后...");
onCurrent("setLoadingTip", (flag: boolean) => {
  loadingTips.value = flag ? "文档导入中,请稍后..." : "";
  setLoading(flag);
});

// 继承的数据和类型
/***
 * @submitArticle // 点击确定的方法
 *
 */

// 定义数据
// 文章定义
const title = ref("");
const content = ref("");
const valueHtml = ref();

// 最大字数的检测和显示
// 当前字数
const currentWordCount = ref<number>(0);
// 当前有效字数
const currentValidWordCount = ref<number>(0);
const maxLength = 5000;
const maxTitleLength = 40;
const isExceededMax = ref<boolean>(false);
// 当前的是否有敏感词
const isSensitive = ref<boolean>(false);
// 当前有效内容
const currentValidImgCount = ref<number>(0);

// 返回顶部/发布设置
const scrollBottom = ref<any>(null);
const scrollTop = ref<any>(null);
const backTop = ref<any>(false);

const tipModelShow = ref<boolean>(false);
const tipChildShow = ref<boolean>(false);

// 设置文本内容
const setHtml = (html) => {
  const editor = editorRef.value;
  editor.focus();
  try {
    // 尝试设置HTML内容
    editor.setHtml(html);
    // 定位光标到最后
    editor.focus(true);
  } catch (error) {
    console.error("设置HTML内容时出错:", error);
  }
};
// 插入文本内容
const dangerouslyInsertHtml = (html) => {
  const editor = editorRef.value;
  try {
    // 尝试插入HTML内容
    editor.dangerouslyInsertHtml(html);
  } catch (error) {
    console.error("插入HTML内容时出错:", error);
  }
};

  // 使用 watchEffect 设置初始值
  watchEffect(async () => {
    if (props.articleData) {
      // 数据变化了先取缓存再看数据
      const data = getItem(`article_${props.articleId}`) || props.articleData;
      historyDetialNew.value = props.articleData;
      setLoading(true);
      await nextTick();

      const contentData = data?.content;
      const titleData = data?.title;
      if (contentData) {
        // 获取图片数量
        const imagesCount = data.images?.length;
        if (imagesCount) {
          currentValidImgCount.value = imagesCount; // 设置当前有效图片数量
          imageInfoArray.value = data.images;
        }
        editorFocus();
        setHtml(contentData);
      }
      if (titleData) {
        title.value = titleData;
      }
      // 获取话题和@的初始化数据
      if (data && data?.atUsers && data?.atUsers.length > 0) {
        atUsersData.value = data.atUsers;
      }
      if (data && data?.subjectTalks && data?.subjectTalks.length > 0) {
        // console.log('原始话题：', data?.subjectTalks);
        topicTalksData.value = data.subjectTalks;
      }
      // 获取图片的数量
      imageInfoArray.value = data?.images;

      setLoading(false);
    }
  });

  const editorValueRef = ref<any>(null);

  // 编辑按钮是否可用  都有值的时候可用
  const priceNumber = computed(() => {
    return articleStore.getCheckedItemDetail.price;
  });
  // 有图片也算有值
  const disabledFlag = computed(() => {
    const type = props?.articleType;
    const price = articleStore.getCheckedItemDetail.price;
    // console.log('文章价格：', price);

    // 检查 content.value 是否只包含空格或换行，不包含任何有效内容
    let wordCountCondition = false;

    if (type === 'order') {
      // 对于 order 类型，字数在 1000 到 5000 之间为达标
      // 2025年1月23日  修改最少字数为200字
      wordCountCondition = !(currentWordCount.value >= minOrderWordLimit.value && currentWordCount.value <= 5000);
    } else if (type === 'article') {
      // 对于 article 类型，字数在 1 到 5000 之间为达标
      let isWordCountValid = currentWordCount.value >= 1 && currentWordCount.value <= 5000;
      // 付费文章不能少于500字
      if (price && price > 0) {
        isWordCountValid = currentWordCount.value >= 500 && currentWordCount.value <= 5000;
      }
      // const hasImages = currentValidImgCount.value > 0;
      wordCountCondition = !isWordCountValid;
    }

    return (
      !title.value || // 无标题
      isSensitive.value || // 存在敏感词
      wordCountCondition // 字数没有达标
    );
  });

  const uploadImgFlag = ref(false);

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 工具栏配置
const toolbarConfig: Partial<IToolbarConfig> = {
  excludeKeys: [
    "group-image",
    "group-video",
    "fullScreen",
    "codeBlock",
    "todo",
    "fontFamily",
  ],
};

// 创建编辑器
const editorConfig: any = {
  placeholder: "请输入正文……",
  scroll: false, // 禁止编辑器滚动
  hoverbarKeys: {
    // 在编辑器中，选中链接文本时，要弹出的菜单
    link: {
      menuKeys: [
        "editInsertLink",
        "unLink",
        "viewLink",
        "convertToLinkCard", // 增加 '转为链接卡片'菜单
      ],
    },
    // 在编辑器中选中文本的时候弹出的菜单
    text: {
      // menuKeys: ['headerSelect', 'bold'],
      menuKeys: [],
    },
    image: {
      menuKeys: [
        "imageWidth30",
        "imageWidth50",
        "imageWidth100",
        "deleteImage",
      ],
    },
    "link-card": {
      menuKeys: [
        "editLinkCardMenu",
        "unlinkCardMenu",
        "viewlinkCardMenu",
        "convertLinkCardToLink",
      ],
    },
  },
  MENU_CONF: {
    uploadImage: {
      // 单个文件的最大体积限制
      maxFileSize: 5 * 1024 * 1024, // 5M
      // 自定义上传
      timeout: 10 * 1000, // 10 秒
      async customUpload(file: File, insertFn: any) {
        // file 即选中的文件

        setLoading(true);
        loadingTips.value = "图片上传中,请稍后...";
        const imageUrl = await uploadImageToAliOS(file);
        const editor = editorRef.value;
        const p = { type: "paragraph", children: [{ text: "" }] };
        // 插入一个p来换行
        // Transforms.insertNodes(editor, p, { mode: 'highest' });
        insertFn(imageUrl);
        uploadImgFlag.value = true;
        setLoading(false);
        // 插入一个p来换行
        Transforms.insertNodes(editor, p, { mode: "highest" });
      },
    },
    uploadAttachment: {},
    lineHeight: {
      lineHeightList: ["1", "1.5", "2", "2.5"],
    },
    // '转为链接卡片'菜单的配置
    convertToLinkCard: {
      async getLinkCardInfo(linkText: string, linkUrl: string, target: any) {
        return new Promise((resolve) => {
          setTimeout(() => {
            const info = {
              title: linkText,
              link: linkUrl,
              iconImgSrc: "",
              target,
            };
            resolve(info);
          }, 100);
        });
      },
    },
  },
  // 附加的方法
  EXTEND_CONF: {
     mentionConfig:
        props.articleType == 'order'
          ? {}
          : {
              showTopicModal: showTopicModal,
              hideTopicModal: hideTopicModal,
              showAtModal: showAtModal,
              hideAtModal: hideAtModal,
            },
      insertLinkConfig: {
        showInsertArticleModal: showInsertArticleModal,
        hideInsertArticleModal: hideInsertArticleModal,
      },
    uploadDocxConfig: {
      showUploadDocxModal: showUploadDocxModal,
      hideUploadDocxModal: hideUploadDocxModal,
    },
    draftHistoryConfig: {
      showDraftHistoryModal: showDraftHistoryModal,
      hideDraftHistoryModal: hideDraftHistoryModal,
    },
  },
};

// 注册自定义dom节点
registerNode();

// 编辑器相关的判断
const handleCreated = (editor: any) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
  registerMenu(editorRef.value, toolbarConfig, props.articleType); // 注册自定义菜单
  // 这里必须要注册事件监听
  // initEditorEventListener(editor);
  // 执行页面渲染
  editorRef.value.history.undos.length = 0;
  editorRef.value.history.redos.length = 0;
  // 定位光标到最后
  editor.focus(true);
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  let editor = editorRef.value;
  if (editor && editor.destroy) {
    editor.destroy();
    editor = null;
  }
});

const titleTimer = ref<any>(); // 标题输入的定时器
const handleInputTitle = debounce((value) => {
  const trimmedValue = value.replace(/\s+/g, ""); // 移除所有空白字符
  title.value = trimmedValue.substring(0, maxTitleLength); // 截取前40个字符
    if (titleTimer.value) {
      clearTimeout(titleTimer.value); // 清除之前的定时器
    }
    titleTimer.value = setTimeout(() => {
      contentEdit('bt');
    }, 1 * 1000); // 1秒后调用contentEdit
  // 存储数据
  setItem(`article_${props.articleId}`, {
    title: title.value,
    content: content.value,
  });
}, 5);

// 编辑器内容、选区变化时的回调函数。 正文
const contentTimer = ref<any>(); // 内容输入的定时器
const handleChange = (
  editor: {
    [x: string]: any;
    getHtml: any;
    children: any;
  },
  event: { preventDefault: () => void }
) => {
  // console.log('键盘事件handleChange');
  const html = editor.getHtml();
  content.value = html;
  // 检测输入的文字  这里做一个防抖截留
  getCurrentWordCount(editor);
  // 看文本的图片张数
  // imgCurrentImages(editor);
  // 检测当前焦点所在的地方
  // getNodeEntries(editor);
    // 必须要内容发生变化的时候才调用
    if (contentTimer.value) {
      clearTimeout(contentTimer.value); // 清除之前的定时器
    }
    contentTimer.value = setTimeout(() => {
      if (
        historyDetialNew.value &&
        (!Object.is(historyDetialNew.value.content, content.value) ||
          !Object.is(historyDetialNew.value.title, title.value))
      ) {
        contentEdit('zw');
        // console.log('内容变化了，调用存储草稿的接口');
      } else {
        // console.log('触发了change，但是内容没有发生变化');
      }
    }, 1 * 1000); // 1秒后调用contentEdit
    // 这里直接用缓存存储所有的文本信息
  // 其中key值是article_articleId value是内容
  setItem(`article_${props.articleId}`, {
    title: title.value,
    content: content.value,
  });
};

const historyTimer = ref<any>(); // 保存历史记录的定时器

// 组件销毁后执行的顺序
const handleDestroyed = (editor: any) => {
  // 这里需要销毁编辑器
  if (editor && editor.destroy) {
    editor.destroy();
    editor = null;
  }
};

// 组件第一次进来获取到焦点
const handleFocus = (editor: any) => {
  if (!editor.isFocused()) {
    editor.focus();
  }
  // 挂载到windows上
  (window as any).wangEditor = editor;
};

const handleBlur = (editor: any) => {
  // console.log('编辑器失去焦点');
};
const customAlert = (s: string, t: string) => {
  const type = ["success", "info", "warning", "error"].includes(t) ? t : "info";
  (Message as any)[type](s);
};

// 自定义粘贴内容。可阻止编辑器的默认粘贴，实现自己的粘贴逻辑。
const customPaste = async (
  editor: IDomEditor,
  event: ClipboardEvent,
  callback: Function
): Promise<boolean> => {
  // 阻止默认的粘贴行为
  event.preventDefault();

  // 获取剪切的截图文件
  const files = event.clipboardData.files;
  if (files.length > 0) {
    const imageFile = files[0];
    // 进行处理剪切的截图文件的操作
    const imageUrl = await uploadImageToAliOS(imageFile);
    const imgHtml = '<img src="' + imageUrl + '" alt="图片" />';
    editor.dangerouslyInsertHtml(imgHtml);
  }

  // 获取粘贴的数据
  let html = event.clipboardData.getData("text/html");
  let text = event.clipboardData.getData("text/plain");
  let rtf = event.clipboardData.getData("text/rtf");

  // 如果HTML内容存在，则优先处理HTML内容
  if (html) {
    // 处理图片数据
    const { innerHtml } = await handlePasteImage(html, rtf);
    // 处理html文本内容
    const text = await handlePasteHtmlStyle(innerHtml);
    // 如果处理后的HTML内容为空，则直接插入纯文本内容
    // 将处理后的HTML内容插入编辑器
    editor.dangerouslyInsertHtml(text);
    return false;
  } else if (text && !html) {
    callback(false);
    event.preventDefault();
    // 如果只有纯文本数据，直接插入
    editor.insertText(text);
    return false;
  }
  return false;
};

// 点击确定文章的接口
const handleSubmit = async () => {
  tipChildShow.value = true;
  tipModelShow.value = true;
};

// 设置字数颜色 #bfc8d5浅灰  #8491a5正常深灰  red超出
const wordCountColor = computed(() => {
  const styles: any = {
    order_0to999: { color: "#bfc8d5", fontWeight: "normal" },
    order_1000tomax: { color: "#8491a5", fontWeight: "normal" },
    order_maxplus: { color: "red", fontWeight: "bold" },
    article_0: { color: "#bfc8d5", fontWeight: "normal" }, // 特别处理article类型下的字数为0
    article_1tomax: { color: "#8491a5", fontWeight: "normal" },
    article_maxplus: { color: "red", fontWeight: "bold" },
    default: { color: "#8491a5", fontWeight: "normal" }, // 默认样式
  };

  const type = props?.articleType;
  let key;

    if (type === 'order') {
      key =
        currentWordCount.value <= 999
          ? 'order_0to999'
          : currentWordCount.value <= maxLength
            ? 'order_1000tomax'
            : 'order_maxplus';
    } else if (type === 'article') {
      key =
        currentWordCount.value === 0
          ? 'article_0'
          : currentWordCount.value <= maxLength
            ? 'article_1tomax'
            : 'article_maxplus';
    } else {
      key = 'default'; // 其他类型默认样式
    }

  return styles[key];
});

// 输入的字数
const getCurrentWordCount = (editor: any) => {
  // 获取文本的内容
  const text = editor.getText().replace(/\n|\r/gm, "");
  currentWordCount.value = text.length;
  const html = editor.getHtml();

    const trimmedContent = html && filterHtmlTagsAndConvertToSpace(html).trim().replace(/<br>/g, '');
    currentValidWordCount.value = trimmedContent.length;
  };
  // 获取文本的图片数量
  const imgCurrentImages = async (editor: any) => {
    const html = editor.getHtml();
    let tempDiv = document.createElement('div');
    tempDiv.innerHTML = html;
    const imgTags = tempDiv.querySelectorAll('img');
    const currentValidImg = props.articleData.images.length;
    if (currentValidImg !== imgTags.length) {
      // 图片数量发生变化
      // console.log('图片数量发生变化');
      await sleep(500);
      // 调用编辑接口
      await contentEdit('zw');
      // 重新更新值
      currentValidImgCount.value = imgTags.length;
    }
  };
  // 编辑器获取焦点
  const editorFocus = () => {
    const editor = editorRef.value;
    if (!editor.isFocused()) {
      editor.focus();
    }
  };

const setLoadingFlag = (flag: boolean) => {
  setLoading(flag);
};

// 自定义菜单的操作
// 导入文档
const uploadDocxConfirm = async (htmlContent: any) => {
  const editor = editorRef.value;
  if (!editor.isFocused()) {
    editor.focus();
  }
  if (htmlContent) {
    uploadDocxVisible.value = false;
    dangerouslyInsertHtml(htmlContent);
    content.value = htmlContent;
  }
};
const uploadDocxCancel = () => {
  uploadDocxVisible.value = false;
  const editor = editorRef.value;
  editor.focus();
};

// 插入话题
const insertTopicRef = ref<any>();
const topicTalksData = ref<any>([]); // 全部插入的话题,之前存储的话题也需要保存起来

const insertTopicConfirm = async () => {
  const editor = editorRef.value;
  if (!editor.isFocused()) {
    editor.focus();
  }
  const topicData = await insertTopicRef.value?.getSelectedTopics();
  if (topicData) {
    topicData.map(async (topic, index) => {
      await sleep(300);
      const topicLink = `/topic?name=${topic.name}`;
      const topicName = `#${topic.name}#`;
      const topicTarget = "_topic";
      // 一次性插入多个，只有第一个算调键盘调起，需要删除前一个，后面的都不需要删除，算click
      if (insertTopicType.value == "keyboard") {
        // 第一个跟随keyboard走，后面的都算click
        if (index == 0) {
          insertTopicType.value = "keyboard";
        } else {
          insertTopicType.value = "click";
        }
      }
      insertMention(
        editor,
        topicName as string,
        topicLink as string,
        topicTarget,
        insertTopicType.value
      );
    });
    topicTalksData.value = [...topicTalksData.value, ...topicData];
  }
  insertTopicVisible.value = false;
};
const insertTopicCancel = () => {
  insertTopicVisible.value = false;
  const editor = editorRef.value;
  if (!editor.isFocused()) {
    editor.focus();
  }
};
// 插入@
const insertAtRef = ref<any>();
const atUsersData = ref<any>([]); // 全局@的人员对象
const insertAtConfirm = async () => {
  const editor = editorRef.value;
  if (!editor.isFocused()) {
    editor.focus();
  }
  const AtData = await insertAtRef.value?.getSelectedAts();
  // console.log('需要插入的@联系人：', AtData);
  if (AtData) {
    AtData.map(async (atItem, index) => {
      await sleep(300);
      // console.log('插入链接：', atItem);
      const atLink = `/at?userId=${atItem.webUserId}&name=${atItem.nickname}`;
      const atName = `@${atItem.nickname}`;
      const atTarget = "_at";
      // 一次性插入多个，只有第一个算调键盘调起，需要删除前一个，后面的都不需要删除，算click
      if (insertAtType.value == "keyboard") {
        // 第一个跟随keyboard走，后面的都算click
        if (index == 0) {
          insertAtType.value = "keyboard";
        } else {
          insertAtType.value = "click";
        }
      }
      insertMention(
        editor,
        atName as string,
        atLink as string,
        atTarget,
        insertAtType.value
      );
    });
    atUsersData.value = [...atUsersData.value, ...AtData];
  }

  insertAtVisible.value = false;
  console.log("插入@后");
};
const insertAtCancel = () => {
  insertAtVisible.value = false;
  const editor = editorRef.value;
  editor.focus();
};

// 打开历史
// 初始化加载标志为 false
const inputTimer = ref<any>(null);
let cleanup: any;
onMounted(() => {
  // 确保 scrollTop.value 已经指向了实际的 DOM 节点
  if (scrollTop.value) {
    const handleScroll = () => {
      if (scrollTop.value.scrollTop === 0) {
        backTop.value = false;
      } else {
        backTop.value = true;
      }
    };

    scrollTop.value.addEventListener("scroll", handleScroll);

    cleanup = () => {
      if (scrollTop.value) {
        scrollTop.value.removeEventListener("scroll", handleScroll);
      }
    };
  }
});

onUnmounted(async () => {
  if (cleanup) {
    cleanup();
  }
  console.log("组件卸载了，要离开页面");

  // 清除定时器以防内存泄漏
  if (inputTimer.value) {
    clearTimeout(inputTimer.value);
    inputTimer.value = null;
  }
  if (titleTimer.value) {
    clearTimeout(titleTimer.value);
    titleTimer.value = null;
  }
  if (contentTimer.value) {
    clearTimeout(contentTimer.value);
    contentTimer.value = null;
  }
  if (historyTimer.value) {
    clearTimeout(historyTimer.value);
    historyTimer.value = null;
  }
});
  const toggleScrollPosition = debounce(() => {
    if (props?.articleType === 'article') {
      if (backTop.value) {
        // 滚动到顶部
        scrollTop.value.scrollTo({
          top: 0,
          behavior: 'smooth',
        });
        backTop.value = false;
      } else {
        // console.log('scrollBottom', scrollBottom.value);
        // 滚动到底部
        scrollBottom.value.scrollIntoView({ behavior: 'smooth' });
        backTop.value = true;
      }
    } else if (props?.articleType === 'order') {
      // 始终滚动到顶部
      scrollTop.value.scrollTo({
        top: 0,
        behavior: 'smooth',
      });
    }
  }, 100);
</script>

<script lang="ts">
export default {
  name: "articleEditor",
};
</script>
